package com.example;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.dao.Constants;
import com.example.util.MD5Util;
import com.example.util.MySessionContext;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.List;

/******************************
 *
 * @Description: Controller基类
 * @author majingmin
 * @date 2014-5-30 上午10:39:23
 */
public abstract class BaseController {

    private static Logger logger = LoggerFactory.getLogger(BaseController.class);

    public static final String FAIL = "fail";
    public static final String LIST = "list";
    public static final String STATUS = "status";
    public static final String WARN = "warn";
    public static final String SUCCESS = "success";
    public static final String ERROR = "error";
    public static final String MESSAGE = "message";
    public static final String CONTENT = "content";
    public static final String DATA = "data";
    public static final String ERRORCODE = "errorcode";
    public static final String ERRORMSG = "errormsg";
    private static final String DEFAULT_ENCODE = "UTF-8";
    private static final String ip = "http://localhost:8080/";

    /**
     * 获取提交参数，取不到就以空字符串代之
     *
     * @param key
     * @return
     */
    protected String getParameter(HttpServletRequest request, String key) {
        return request.getParameter(key) == null ? "" : request.getParameter(key).trim();
    }

    /**
     * 获取提交参数，取不到就报参数以定义字符串代替
     *
     * @param key
     * @return
     */
    protected String getParameterForDefValue(HttpServletRequest request, String key, String defValue) {

        return StringUtils.isBlank(request.getParameter(key)) ? defValue : request.getParameter(key).trim();
    }

    /**
     * 获取提交参数，取不到就报参数无法获取之异常
     *
     * @param key
     * @return
     */
    protected String getParameter(HttpServletRequest request, String key, boolean isNeed) {
        String result = getParameter(request, key);
        if (isNeed && result.equals(""))
            throw new RuntimeException("无法获取参数异常");
        return result;
    }


    public Object getSessionValue(HttpServletRequest request ,String paren){
        String sessionId = request.getParameter("session_id");
        HttpSession session = MySessionContext.getSession(sessionId);
        return session.getAttribute(paren);
    }

    /**
     * 自动获取参数
     * @return
     */
    public Map<String, String> getRequestMap( HttpServletRequest request ) {
        Map<String, String> resultMap = new HashMap<String, String>();
        Map<?, ?> requestMap = request.getParameterMap();
        for ( Object key : requestMap.keySet() ) {
            resultMap.put( String.valueOf(key), request.getParameter(String.valueOf(key)).trim() );
        }
        return resultMap;
    }



    public String createJson(Object data) {
           String jsonStr = JSONObject.toJSONString(data, SerializerFeature.DisableCircularReferenceDetect);
           return jsonStr;
    }
    
    public String createJson(String errorCode, String errorMessage)
    {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put(Constants.ERROR_CODE_KEY, errorCode);
        resultMap.put(Constants.ERROR_MSG_KEY, errorMessage);
        return createJson(resultMap);
    }

    protected String dataTableJson(int totalCount, List<?> dataList) {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("iTotalDisplayRecords", totalCount);
        data.put("iTotalRecords", totalCount);
        data.put("aaData", dataList == null ? Collections.EMPTY_LIST : dataList);
        Map<String, Object> map = new HashMap<String, Object>();
        if (CollectionUtils.isEmpty(dataList)) {
            map.put("result", ERROR);
        } else {
            map.put("result", SUCCESS);
        }
        map.put("data", data);
//        return map;
        return createJson(map);
    }

    protected Map<String, Object> dataJson(int totalCount, List<?> dataList) {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("totalCount", totalCount);
        data.put("aaData", dataList == null ? Collections.EMPTY_LIST : dataList);
        Map<String, Object> map = new HashMap<String, Object>();
        if (CollectionUtils.isEmpty(dataList)) {
            map.put("result", ERROR);
        } else {
            map.put("result", SUCCESS);
        }
        map.put("data", data);
        return map;
    }

    protected Map<String, Object> data2json(List<?> data) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (CollectionUtils.isEmpty(data)) {
            map.put("result", ERROR);
        } else {
            map.put("result", SUCCESS);
        }
        map.put("data", data);
        return map;
    }

    /**
     * 根据请求参数获取MD5验证串
     * @param treeMap  参数
     * @param secretKey 密钥
     * @return
     */
    public String getMD5Sign(Map<String, String> treeMap,String secretKey) {
        StringBuffer sb = new StringBuffer() ;
        Iterator<String> ite = treeMap.keySet().iterator() ;
        while(ite.hasNext()){
            String key = ite.next() ;
            String value = treeMap.get(key) ;
            if(StringUtils.isNotBlank(value)){
                sb.append(key).append(value) ;
            }
        }
        if(StringUtils.isNotBlank(secretKey)) {
            sb.append(secretKey);
        }
        return MD5Util.md5Hex(sb.toString(), DEFAULT_ENCODE).toUpperCase();
    }

    // 将 s 进行 BASE64 编码
    public static String getBASE64(String s) {
        if (s == null)
            return null;
        return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
    }

    // 将 BASE64 编码的字符串 s 进行解码
    public static byte[] getFromBASE64(String s) {
        if (s == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();

        try {
            byte[] b = decoder.decodeBuffer(s);
            // byte[] b = Base64.decode(s);
            // return new String(b);

            return b;
        } catch (Exception e) {
            return null;
        }
    }

    public void cut(String srcpath,String imageType,int x,int y,int width,int height,String subpath) throws IOException {
        FileInputStream is = null;
        ImageInputStream iis = null;
        try {
            is = new FileInputStream(srcpath);
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(imageType);
            ImageReader reader = it.next();
            iis = ImageIO.createImageInputStream(is);
            reader.setInput(iis, true);
            ImageReadParam param = reader.getDefaultReadParam();
            Rectangle rect = new Rectangle(x, y, width, height);
            param.setSourceRegion(rect);
            BufferedImage bi = reader.read(0, param);
            ImageIO.write(bi,imageType, new File(subpath));
        } finally {
            if (is != null)
                is.close();
            if (iis != null)
                iis.close();
        }
    }

}